﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Thingpower.SS.EduOnline.Provider;
using Thingpower.SS.EduOnline.Core;

namespace Thingpower.SS.EduOnline.WebAPI
{
    [RoutePrefix("eduonline/api/member")]
    public class MemberController : ApiController
    {
        [HttpGet, Route("hello")]
        public IHttpActionResult GetString()
        {
            return Ok("hello");
        }

        [HttpGet, Route("resetpwd")]
        public IHttpActionResult ChangePassword([FromUri]string account, [FromUri]string pwd)
        {
            string error = "";
            bool isUsernameExists = false;
            bool isMobileExists = false;
            bool isSuccess = false;

            isUsernameExists = EduOnlinePlugin.Instance.UserApi.IsUserNameExists(account);
            isMobileExists = EduOnlinePlugin.Instance.UserApi.IsMobileExists(account);

            if (isUsernameExists)
            {
                isSuccess = EduOnlinePlugin.Instance.UserApi.ChangePassword(account, pwd, out error);
            }else if (isMobileExists)
            {
                string username;
                username = EduOnlinePlugin.Instance.UserApi.GetUserInfoByMobile(account).UserName;
                isSuccess = EduOnlinePlugin.Instance.UserApi.ChangePassword(username, pwd, out error);
            }
            else
            {
                error = "用户名或手机不存在";
            }

            

            if (isSuccess)
            {
                return Ok("success");
            }
            else
            {
                return Ok(error);
            }
        }

        [HttpPost, Route("login")]
        public IHttpActionResult Login([FromBody] ActionsLoginBody body)
        {
            try
            {
                //var request = new AuthRequest();
                var request = EduOnlinePlugin.Instance.Request;

                string userName;
                string errorMessage;
                
                if (!EduOnlinePlugin.Instance.UserApi.Validate(body.Account, body.Password, out userName, out errorMessage))
                {
                    UserDAO.UpdateLastActivityDateAndCountOfFailedLogin(userName);
                    return BadRequest(errorMessage);
                }

                var userInfo = EduOnlinePlugin.Instance.UserApi.GetUserInfoByUserName(userName);
                var accessToken = request.UserLogin(userName, body.IsAutoLogin);
                UserDAO.UpdateLastActivityDateAndResetCountOfFailedLogin(userName);

                return Ok(new
                {
                    Value = userInfo,
                    AccessToken = accessToken
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("validatecode")]
        public IHttpActionResult ValidateMessageCode([FromUri]string aom, [FromUri]string code, [FromUri]string encryptionCode, [FromUri]string type, [FromUri]string pwd)
        {
            //在AliyunSMS中返回一个加密的验证码，然后在前端页面中验证时发送填写的验证码和收到的加密验证码，在本接口中进行验证，如果验证通过，则进行后续操作，否则中断操作并提示验证码错误
            

            try
            {
                string mobile = null;
                if (type == "1")
                {
                    mobile = EduOnlinePlugin.Instance.UserApi.GetUserInfoByAccount(aom).Mobile;
                }
                if (type == "2")
                {
                    mobile = aom;
                }

                char[] reverse = mobile.Substring(3, 8).Reverse().ToArray();
                string maskCode = new string(reverse);
                int responseCode = int.Parse(maskCode) - int.Parse(code);

                if (!string.IsNullOrEmpty(mobile) && responseCode.ToString() == encryptionCode)
                {
                    string error = "";
                    bool isSuccess = true;
                    if(type == "1")
                    {
                        isSuccess = EduOnlinePlugin.Instance.UserApi.ChangePassword(aom, pwd, out error);
                    }
                    
                    return Ok(isSuccess ? "success" : error);
                }
                else
                {
                    return Ok("短信验证码错误");
                }
            }
            catch(Exception ex)
            {
                return InternalServerError(ex);
            }
            
            
        }
    }

    public class ActionsLoginBody
    {
        public string Account { get; set; }
        public string Password { get; set; }
        public bool IsAutoLogin { get; set; }
    }
}
